import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { asyncRoutes } from '@/router'

const whiteList = ['/login', '/404'] // no redirect whitelist

// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  if (store.getters.token) {
    if (to.path === '/login') {
      // 跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles.menus)// 数组，不确定需要看匹配
        // console.log(asyncRoutes)// 总的八个数组
        const fliterRoutes = asyncRoutes.filter(item => {
          // return,includes查看是否有权限
          return roles.menus.includes(item.name)
        })// 筛选后的路由
        store.commit('user/setRoutes', fliterRoutes)
        // console.log(fliterRoutes)
        router.addRoutes([...fliterRoutes, { path: '*', redirect: '/404', hidden: true }])// 添加动态路由信息到路由表,删除静态路由的404，把404展开后添加到动态路由后面
        // router添加动态路由之后，需要转发一下
        next(to.path)// 目的是让路由拥有信息，router的已知缺陷
        // 表示再转发一次
      } else {
        next()// 放过
      }
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')// 没有白名单，中转登录页
      NProgress.done()
    }
  }
})

// 路由后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
